//导入用户集合构造函数
const { User } = require('../../model/user')
const bcrypt = require('bcrypt')

module.exports = async(req, res) => {
    //接受参数
    const { email, password } = req.body
    if (email.trim().length == 0 || password.trim().length == 0) {
        return res.status(400).render('home/error', { msg: '邮件地址或密码错误' })
    }
    let user = await User.findOne({ email: email })
    if (user) {
        //查询到了邮箱,比对密码
        let isValid = await bcrypt.compare(password, user.password)
        if (isValid) {
            req.session.username = user.username
            req.session.role = user.role
                // res.send('登陆成功')

            req.app.locals.userInfo = user


            res.redirect('/home/')




        } else {
            res.status(400).render('home/error', { msg: '邮箱地址或密码错误' })

        }

    } else {
        res.status(400).render('home/error', { msg: '邮箱地址或密码错误' })

    }
}